// src/stores/userStore.ts
import { defineStore } from "pinia";
import type { LoginSing_from, User } from "@/types/User";
import type { Status } from "@/types/Status";
import { UserAPI } from "@/api/UserAPI";

type State = {
  userinfo:{
    result: Partial<User>;
    status: Status;
  }
  
};

type Getters = {};

type Actions = {
   //登录
   BkLogin(login_from:LoginSing_from):Promise<void>;
   //注册
   BkSign(sign_from:LoginSing_from):Promise<void>;
   //获取用户收藏列表
   getCollect_list():Promise<void>;
};

export const useUserStore = defineStore<"user", State, Getters, Actions>(
  "user",
  {
    state: () => ({
      userinfo:{
        result: {},
        status:'idle'
      }
    }
     
     ),
     actions:{
      //登录
      async BkLogin(login_from:LoginSing_from){
        //更新数据加载状态
        this.userinfo.status = 'loading'
          //发送请求获取数据
          const response = await UserAPI.BkLogin(login_from) 
        if(response.code===200){
                // 储存用户信息
                this.userinfo.result = response.data
             // 更新数据加载状态
               this.userinfo.status = "success";
        }else{
            //储存错误信息
           this.userinfo.result = response.data
           // 更新数据加载状态
           this.userinfo.status = "error";
      
        }
        
       },
      //注册
      async BkSign(sign_from:LoginSing_from){
        //更新数据加载状态
        this.userinfo.status = 'loading'
          //发送请求获取数据
          const response = await UserAPI.BkSign(sign_from) 
        if(response.code===200){
             // 储存用户信息
                this.userinfo.result = response.data
             // 更新数据加载状态
               this.userinfo.status = "success";
        }else{
            //储存错误信息
           this.userinfo.result = response.data
           // 更新数据加载状态
           this.userinfo.status = "error";
      
        }
        
       },
      //用户收藏文章列表
      async getCollect_list(){
        this.userinfo.status = 'loading'
        //发送请求获取数据
        const response = await UserAPI.collection_list() 
        
      if(response.code===200){
           // 储存用户信息
              this.userinfo.result.collects_list = response.data
           // 更新数据加载状态
             this.userinfo.status = "success";
      }else{
          //储存错误信息
         // 更新数据加载状态
         this.userinfo.status = "error";
    
      }
      }
      
     },
    persist: true,
  }
);